<template>
  <div class="page-container">
    <el-container>
      <el-aside width="280px" class="page-aside" v-drag v-collapse>
        <div class="tree-box">
          <el-row>
            <el-input
              placeholder="流程搜索"
              v-model="filterText"
              style="margin-right: 10px"
              clearable
            ></el-input>
          </el-row>
        </div>
        <el-row class="page-aside-grow">
          <el-tree
            ref="tree"
            class="filter-tree"
            :data="treeData"
            node-key="id"
            :props="treeProps"
            :highlight-current="true"
            :default-expanded-keys="['0']"
            @node-click="nodeClick"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
          ></el-tree>
        </el-row>
      </el-aside>
      <el-main style="--el-main-padding: 10px;">
        <el-form
          :model="batchFormData"
          label-width="0px"
          ref="batchDataForm"
        >
          <el-table
            class="edit-table line-table"
            width="100%"
            :data="batchFormData.list"
            :border="true"
            header-align="center"
            :show-overflow-tooltip="{
              'effect': 'light',
              'raw-content': false,
              'placement': 'bottom',
              'popper-class': 'padding-10-15'
            }"
          >
            <el-table-column
              label="节点名称"
              header-align="center"
              align="center"
              min-width="120"
              prop="name"
            />
            <el-table-column
              label="节点处理人"
              header-align="center"
              min-width="240"
              :show-overflow-tooltip="false"
            >
              <template #header>
                <span>节点处理人</span>
                <el-tooltip>
                  <ac-icon iconId="018dca8ec9890493be26" style="margin-left: 5px"/>
                  <template #content>
                    <div>输入：以手工输入的方式确定节点的处理人。</div>
                    <div>节点：取离此节点最近一个“所在节点”的处理人为节点处理人。</div>
                    <div>脚本：通过脚本的方式获取处理人，在脚本中返回节点处理人。</div>
                    <div>字段：获取当前登录人所在部门的字段值作为节点处理人。</div>
                    <div>注：节点处理部门、节点处理人二选一，节点处理部门、节点处理人都有值时以节点处理人为准。</div>
                  </template>
                </el-tooltip>
              </template>
              <template #default="scope">
                <div class="line-box">
                  <div class="line-item1">
                    <el-form-item>
                      <ac-dict-select
                        v-model="scope.row.dealManType"
                        placeholder="请选择"
                        dictCode="dictFlowDealManType"
                      />
                    </el-form-item>
                  </div>
                  <div class="line-item2" v-if="scope.row.dealManType === '3'">
                    <el-form-item>
                      <el-select
                        v-model="scope.row.dealManNodeId"
                        placeholder="--请选择--"
                        filterable
                        clearable
                        @change="changeManNode(scope.row)"
                      >
                        <el-option
                          v-for="(item, index) in nodeData"
                          :key="index"
                          :label="item.name"
                          :value="item.id"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                  <div class="line-item3">
                    <el-form-item
                      v-if="scope.row.dealManType === '1'"
                      style="width: 100%"
                    >
                      <ac-employee-tree v-model="scope.row.dealManSourceId" />
                    </el-form-item>
                    <el-form-item
                      v-else-if="scope.row.dealManType === '2'"
                      style="width: 100%"
                    >
                      <el-select
                        v-model="scope.row.dealManSourceId"
                        placeholder="--请选择--"
                        filterable
                        clearable
                      >
                        <el-option
                          v-for="(item, index) in nodeData"
                          :key="index"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      v-else-if="scope.row.dealManType === '3' && scope.row.dealManModelId"
                      style="width: 100%"
                    >
                      <ac-remote-select
                        v-model="scope.row.dealManSourceId"
                        data-url="/system/dataField/queryList"
                        :query="{modelId: scope.row.dealManModelId}"
                        idProp="fieldName"
                        nameProp="showName"
                        :loadAll="true"
                      />
                    </el-form-item>
                    <el-form-item
                      v-else-if="scope.row.dealManType === '4'"
                      style="width: 100%"
                    >
                      <ac-tree
                        v-model="scope.row.dealManSourceId"
                        data-url="/system/scriptGroovy/queryTree"
                        type-select="script"
                      />
                    </el-form-item>
                    <el-form-item v-else style="width: 100%">
                      <el-select placeholder="--请选择--" />
                    </el-form-item>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="节点处理部门"
              header-align="center"
              min-width="240"
              :show-overflow-tooltip="false"
            >
              <template #header>
                <span>节点处理部门</span>
                <el-tooltip>
                  <ac-icon iconId="018dca8ec9890493be26" style="margin-left: 5px"/>
                  <template #content>
                    <div>手工输入：以手工输入的方式确定节点的处理部门。</div>
                    <div>节点处理部门：取离此节点最近一个“所在节点”的处理部门为节点处理部门。</div>
                    <div>节点数据：取节点对应填写的数据。</div>
                    <div>脚本：通过脚本的方式获取处理部门，在脚本中返回节点处理部门。</div>
                    <div>注：节点处理部门、节点处理人二选一，节点处理部门、节点处理人都有值时以节点处理人为准。</div>
                  </template>
                </el-tooltip>
              </template>
              <template #default="scope">
                <div class="line-box">
                  <div class="line-item1">
                    <el-form-item>
                      <ac-dict-select
                        v-model="scope.row.dealOrgType"
                        placeholder="请选择"
                        dictCode="dictFlowDealOrgType"
                      />
                    </el-form-item>
                  </div>
                  <div v-if="scope.row.dealOrgType === '3'" class="line-item2">
                    <el-form-item>
                      <el-select
                        v-model="scope.row.dealOrgNodeId"
                        placeholder="--请选择--"
                        filterable
                        clearable
                        @change="changeOrgNode(scope.row)"
                      >
                        <el-option
                          v-for="(item, index) in nodeData"
                          :key="index"
                          :label="item.name"
                          :value="item.id"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                  <div class="line-item3">
                    <el-form-item
                      v-if="scope.row.dealOrgType === '1'"
                    >
                      <ac-organization-tree v-model="scope.row.dealOrgSourceId" />
                    </el-form-item>
                    <el-form-item
                      v-else-if="scope.row.dealOrgType === '2'"
                      style="width: 100%"
                    >
                      <el-select
                        v-model="scope.row.dealOrgSourceId"
                        placeholder="--请选择--"
                      >
                        <el-option
                          v-for="(item, index) in nodeData"
                          :key="index"
                          :label="item.name"
                          :value="item.id"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      v-else-if="scope.row.dealOrgType === '3' && scope.row.dealOrgModelId"
                      style="width: 100%"
                    >
                      <ac-remote-select
                        v-model="scope.row.dealManSourceId"
                        data-url="/system/dataField/queryList"
                        :query="{modelId: scope.row.dealOrgModelId}"
                        idProp="fieldName"
                        nameProp="showName"
                        :loadAll="true"
                      />
                    </el-form-item>
                    <el-form-item
                      v-else-if="scope.row.dealOrgType === '4'"
                      style="width: 100%"
                    >
                      <ac-tree
                        v-model="scope.row.dealOrgSourceId"
                        data-url="/system/scriptGroovy/queryTree"
                        type-select="script"
                      />
                    </el-form-item>
                    <el-form-item v-else style="width: 100%">
                      <el-select placeholder="--请选择--" />
                    </el-form-item>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <el-row
          v-if="batchFormData.flowId"
          style="margin: 10px 0 0 0;"
        >
          <el-col :span="24" style="text-align:right">
            <el-button
              type="primary"
              :loading="editLoading"
              @click="submitBatchForm"
            >保存</el-button>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue';
import api from "@/http/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";

const filterText = ref('');
const treeData = ref([]);
const treeProps = ref({
  children: 'children',
  label: 'name',
  isLeaf: 'leaf'
});
const editLoading = ref(false);
const batchFormData = ref({
  list: []
});
const nodeData = ref([]);

const tree = ref();
const route = useRoute();
const batchDataForm = ref();

watch(() => filterText.value, (val) => {
  tree.value.filter(val);
});

const filterNode = (value, data, node) => {
  if (!value) return true;
  // 叶节点，根据父流程名称来判断
  if (data.leaf === true && node.parent != null && node.parent.data != null) {
    const data = node.parent.data;
    return data.name.indexOf(value) !== -1 || (data.code != null && data.code.indexOf(value) !== -1);
  }
  return data.name.indexOf(value) !== -1 || (data.code != null && data.code.indexOf(value) !== -1);
};

const nodeClick = (data, node) => {
  if (node.level > 1) {
    batchFormData.value.flowId = node.data.id;
    loadNodeData(batchFormData.value.flowId);

    nextTick(() => {
      batchDataForm.value && batchDataForm.value.clearValidate();
    });
  }
};

const changeOrgNode = (row) => {
  const node = nodeData.value.find(item => item.id === row.dealOrgNodeId);
  if (node) {
    row.dealOrgModelId = node.modelId;
  }
};

const changeManNode = (row) => {
  const node = nodeData.value.find(item => item.id === row.dealManNodeId);
  if (node) {
    row.dealManModelId = node.modelId;
  }
};

const submitBatchForm = () => {
  batchDataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true
        api.post('/system/flowNode/saveDealMan', batchFormData.value).then(res => {
          if(res.code === '1') {
            loadNodeData(batchFormData.value.flowId);
            ElMessage.success(res.message);
          } else {
            ElMessage.error(res.message);
          }
          editLoading.value = false
        }).catch(() => {
          editLoading.value = false
        })
      }).catch(()=>{})
    } else {
      ElMessage.error('表单数据填写不完整，请检查！');
    }
  })
};

const loadTreeData = () => {
  // 获取本页的操作按钮
  api.post(route.meta.url).then(res => {
    if(res.code === '1') {
      treeData.value = [{id: '0', name: '流程树', children: res.data}];
    } else {
      ElMessage.error(res.message);
    }
  });
};

const loadNodeData = (id) => {
  editLoading.value = true;
  const flowId = id;
  api.post('/system/flowNode/queryList', {flowId: flowId, valid: '1', type: '10'}).then(res => {
    if(res.code === '1') {
      if (res.data.length > 0) {
        batchFormData.value = Object.assign({flowId: flowId}, {list: res.data});
        nodeData.value = res.data;
      } else {
        batchFormData.value = Object.assign({flowId: flowId}, {list: []});
        nodeData.value = [];
      }
    } else {
      ElMessage.error(res.message);
    }
    editLoading.value = false;
  }).catch(() => {
    editLoading.value = false;
  });
}

onMounted(() => {
  loadTreeData();
  batchFormData.value = Object.assign({}, {list: []});
});
</script>

<style scoped lang="scss">
.edit-table.line-table :deep(td:nth-child(1)) .cell{
  white-space: nowrap;
  padding: 0 5px !important;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: 0;
  display: block;
}
.line-box {
  width: 100%;
  display: flex;
  flex-direction: row;
  .line-item1 {
    width: 160px;
    flex-shrink: 0;
  }
  .line-item2, .line-item3 {
    flex-grow: 1;
    width: 50%;
  }
}
</style>